import { queryBrandList, queryProductNum } from '@/services/brand';

export default {
  namespace: 'brand',

  state: {},

  effects: {
    *queryBrandList({ payload }, { call, put, select }) {
      const response = yield call(queryBrandList, payload);

      const ans = response.map(it => ({
        label: it.name,
        value: it.id,
        isLeaf: false
      }));

      yield put({ type: 'setBrandList', payload: ans })
    },
    *queryProductNum({ payload }, { call, put }) {

      const response = yield call(queryProductNum, payload);

      const ans = response.map(it => ({
        label: it.name,
        value: it.id,
        isLeaf: true
      }));

      yield put({ type: 'setProductNum', payload: ans })
    },
    *queryBrandAll({ payload }, { all, put, call }) {
      const [brand, sub] = yield all([
        call(queryBrandList),
        call(queryProductNum, payload)
      ]);

      const subAns = sub.map(it => ({
        label: it.name,
        value: it.id,
        isLeaf: true,
      }));

      const ans = brand.map(it => ({
        label: it.name,
        value: it.id,
        isLeaf: false,
        children: it.id === payload ? subAns : []
      }));

      yield put({ type: 'setBrandList', payload: ans })
    }
  },

  reducers: {
    setBrandList(state, action) {
      return {
        ...state,
        brand: action.payload
      }
    },
    setProductNum(state, action) {
      return {
        ...state,
        sub: action.payload
      }
    }
  },
};
